<?php


namespace App\Console\Commands\Channel;


use Illuminate\Console\Command;

class StageDataCommand extends Command
{
    //命令名
    protected $signature = 'channel:stage-data';

    //命令描述
    protected $description = '渠道分期数据统计';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //查询所有渠道和分期
        $channelStages = app('model_channel_stage')
            ->select('id', 'channel_id')
            ->get();

        foreach ($channelStages as $channelStage) {

            $userWhere = ['channel_stage_id' => $channelStage->id];
            //渠道分期注册用户数
            $registerUserIds = app('model_user')
                ->select('user_id')
                ->where($userWhere)
                ->pluck('user_id')->toArray();

            //渠道分期激活用户数
            $activatedUserCount = app('model_user')
                ->where($userWhere)
                ->where('last_login_time', '>', 0)
                ->count();

            //充值用户数和充值总额
            $registerUserIdChunks = array_chunk($registerUserIds, 1000); //将数组分块，每个子数组的长度是10000
            $rechargeUserIds = [];
            $rechargeTotal = 0;
            foreach ($registerUserIdChunks as $registerUserIdChunk) {
                $rechargeUserIds += app('model_user_recharge')
                    ->select('user_id')
                    ->whereIn('user_id', $registerUserIdChunk)
                    ->where('status', 2)
                    ->groupBy('user_id')->pluck('user_id', 'user_id')->toArray();
                $rechargeTotal += app('model_user_recharge')
                    ->whereIn('user_id', $registerUserIdChunk)
                    ->where('status', 2)
                    ->sum('money');
            }

            //新增或更新数据
            $data = [
                'register_user_count' => count($registerUserIds),
                'activated_user_count' => $activatedUserCount,
                'recharge_user_count' => count($rechargeUserIds),
                'recharge_total' => $rechargeTotal,
            ];

            $where = ['channel_stage_id' => $channelStage->id];
            $channelStageData = app('model_channel_stage_data')
                ->select('channel_stage_id')
                ->where($where)
                ->first();
            if ($channelStageData) {
                app('model_channel_stage_data')
                    ->where($where)
                    ->update($data);
            } else {
                $data['channel_stage_id'] = $channelStage->id;
                $data['channel_id'] = $channelStage->channel_id;
                app('model_channel_stage_data')->insert($data);
            }
        }
    }
}